#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QVBoxLayout>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_port = new HSerialPort();
    m_port->open("COM1");
    m_port->start();

    QVBoxLayout *vLayout=new QVBoxLayout();
    ui->centralwidget->setLayout(vLayout);

    {
        m_cbBox=new QComboBox();
        m_cbBox->addItems(m_port->getAvailablePorts());
        vLayout->addWidget(m_cbBox);
    }
    {
        m_btn=new QPushButton("Open");
        connect(m_btn, &QPushButton::clicked,this,&MainWindow::onSerialPortOpenOrClosed);
        vLayout->addWidget(m_btn);
    }
    {
        m_updatePortsBtn=new QPushButton("Update Ports");
        connect(m_updatePortsBtn, &QPushButton::clicked, this, &MainWindow::onPortsUpdate);
        vLayout->addWidget(m_updatePortsBtn);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onSerialPortOpenOrClosed(bool flag)
{
    if(!flag){
        bool rlt=m_port->open(m_cbBox->currentText());
        if(!rlt){
            qDebug()<<"串口打开失败";
            return;
        }
        m_btn->setText("Close");
        qDebug() << "串口已经打开";
    }else{
        m_port->close();
        m_btn->setText("Open");
    }
}

void MainWindow::onPortsUpdate()
{
    qDebug() << "onPortsUpdate";
    QString curr_port=m_cbBox->currentText();
    m_cbBox->blockSignals(true);
    m_cbBox->clear();
    m_cbBox->addItems(m_port->getAvailablePorts());
    m_cbBox->setCurrentText(curr_port);
    m_cbBox->blockSignals(false);
}
